package core

import (
	"encoding/json"
	"fmt"
	"github.com/xuri/excelize/v2"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"strconv"
	"time"
)

const prefix = "copy_"
const numOne = "1"

// Iphone 向Excel中添加手机归属地信息
func Iphone(path, sheet, iphone string) error {
	abs, err := filepath.Abs(path)
	if err != nil {
		return err
	}

	file, err := excelize.OpenFile(abs)
	if err != nil {
		return err
	}

	wPath := filepath.Join(filepath.Dir(abs), prefix+filepath.Base(abs))
	xlsx := NewXlsx(file)

	nextColumns := xlsx.NextColumns(sheet, 3)
	var tits = []string{"运营商", "省份", "城市"}
	for i, column := range nextColumns {
		_ = file.SetCellValue(sheet, column+numOne, tits[i])
	}

	client := http.Client{
		Timeout: 10 * time.Second,
	}

	for i := 2; true; i++ {
		row := strconv.Itoa(i)

		value, err := file.GetCellValue(sheet, iphone+row)
		if err != nil {
			return err
		}

		if value == "" {
			break
		}

		// 请求接口
		url := fmt.Sprintf("https://c.ruwe.cn/api/phone/belong?phone_number=%s", value)
		res, err := client.Get(url)
		if err != nil {
			return err
		}
		all, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		_ = res.Body.Close()

		info := &Response{}
		err = json.Unmarshal(all, info)
		if err != nil {
			return err
		}

		if info.Status == "0" {
			data := info.Data
			if nil != data {
				_ = file.SetCellValue(sheet, nextColumns[0]+row, data.BelongName)
				_ = file.SetCellValue(sheet, nextColumns[1]+row, data.ProvinceName)
				_ = file.SetCellValue(sheet, nextColumns[2]+row, data.CityName)
			}
		}
	}

	err = file.SaveAs(wPath)
	if err != nil {
		return err
	}

	return nil
}

type Response struct {
	Status string `json:"status"`
	Data   *Data  `json:"data"`
}

type Data struct {
	CityName     string `json:"city_name"`
	BelongName   string `json:"belong_name"`
	ProvinceName string `json:"province_name"`
}
